package com.kyrie.lib_sys.utils.learn.semaphoreDemo;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class semaphoreTest {
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();

        // 创建一个信号量，只允许5个线程同时访问
        final Semaphore semp = new Semaphore(5);

        // 创建8个任务
        for (int i = 0; i < 8; i++) {
            final int emp_num = i;
            Runnable run = new Runnable() {
                public void run() {
                    try {
                        semp.acquire();
                        System.out.println("获得许可，当前工作工人: " + emp_num);

                        Thread.sleep((long) (Math.random() * 10000));
                        semp.release();
                        System.out.println("释放资源，当前空闲机器数量：" + semp.availablePermits());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
            exec.execute(run);
        }
    }
}
